#!/bin/bash

# --- 依赖检查与安装 ---
check_and_install_dependencies() {
    echo "Checking dependencies..."

    # 检查 Java (JDK)
    if ! command -v java &> /dev/null; then
        echo "Java is not installed. Please install JDK 21 and make sure it's in your PATH."
        echo "For Ubuntu, you can use: sudo apt install openjdk-21-jdk"
        exit 1
    else
        JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
        echo "Found Java version $JAVA_VERSION"
        if [[ ! "$JAVA_VERSION" == "21."* ]]; then
            echo "Warning: Java version is not 21. This may cause issues. The recommended version is JDK 21."
        fi
    fi

    # 检查 Maven
    if ! command -v mvn &> /dev/null; then
        echo "Maven is not installed. Attempting to install..."
        sudo apt-get update && sudo apt-get install -y maven
        if ! command -v mvn &> /dev/null; then
            echo "Maven installation failed. Please install it manually."
            exit 1
        fi
        echo "Maven installed successfully."
    else
        echo "Maven is already installed."
    fi

    # 检查 Node.js 和 npm
    if ! command -v npm &> /dev/null; then
        echo "Node.js/npm is not installed. Attempting to install..."
        sudo apt-get update && sudo apt-get install -y nodejs npm
        if ! command -v npm &> /dev/null; then
            echo "Node.js/npm installation failed. Please install it manually."
            exit 1
        fi
        echo "Node.js/npm installed successfully."
    else
        echo "Node.js/npm is already installed."
    fi

    echo "All dependencies are satisfied."
    echo "----------------------------------------"
}

# --- 主程序 ---

# 获取脚本所在目录的绝对路径
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

# 执行依赖检查
check_and_install_dependencies

echo "Starting manager-api..."
cd "$SCRIPT_DIR/main/manager-api"
# 使用 nohup 在后台运行，并将日志重定向到文件
nohup mvn spring-boot:run > "$SCRIPT_DIR/manager-api.log" 2>&1 &
echo "manager-api is starting in the background. Log file: $SCRIPT_DIR/manager-api.log"
echo "Default port: 8002"

echo "----------------------------------------"

echo "Starting manager-web..."
cd "$SCRIPT_DIR/main/manager-web"
# 清理并重新安装依赖以确保环境干净
echo "Cleaning up and reinstalling manager-web dependencies..."
rm -rf node_modules package-lock.json
npm install
if [ $? -ne 0 ]; then
  echo "npm install for manager-web failed. Please check the logs."
  exit 1
fi
# 使用 nohup 在后台运行，并将日志重定向到文件
nohup npm run serve > "$SCRIPT_DIR/manager-web.log" 2>&1 &
echo "manager-web is starting in the background. Log file: $SCRIPT_DIR/manager-web.log"
echo "Default port: 8001"

echo "----------------------------------------"
echo "Services are starting. It may take a few moments for them to be available."
echo "You can check the logs with:"
echo "tail -f $SCRIPT_DIR/manager-api.log"
echo "tail -f $SCRIPT_DIR/manager-web.log"